package com.lanju.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.SMSCaptcha;



@Repository
public class SMSCaptchaDao {

    private static final Log log = LogFactory.getLog(SMSCaptchaDao.class);

    @PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;

    public void persist(SMSCaptcha transientInstance) {
        try {
            entityManager. persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        } 
    }

    public void remove(SMSCaptcha persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public SMSCaptcha merge(SMSCaptcha detachedInstance) {
        try {
            SMSCaptcha result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public SMSCaptcha getById(String  id) {
        try {
            SMSCaptcha instance = entityManager.find(SMSCaptcha.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    /**
     * 获取手机号码五分钟内发送的验证码, 取最新一条数据
     * */
    @SuppressWarnings("unchecked")
	public SMSCaptcha getByPhoneBy5Min(String phone) {
        try {
            Query query = entityManager.createQuery("from SMSCaptcha where phone=?1  and  TIMESTAMPDIFF(SECOND,createTime,now())<300  order by createTime desc").setParameter(1, phone);
            List<SMSCaptcha> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByPhone fail",e);
            throw e;
        }
    }

    @SuppressWarnings("unchecked")
	public List<SMSCaptcha> getList(String adminName, int pageSize, int offset) {
        try {
            StringBuffer sqld = new StringBuffer("from SMSCaptcha s where 1=1 ");
            if(!StringUtils.isEmpty(adminName)){
               sqld.append(" and s.adminname like:n ");
            }
            Query query = entityManager.createQuery(sqld.toString()).setFirstResult(offset).setMaxResults(pageSize);
            if(!StringUtils.isEmpty(adminName)){
                query.setParameter("n", "%"+adminName+"%");
            }
            return query.getResultList();
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return null;
    }
    
    public long getListCount(String adminName) {
        try {
            StringBuffer sqld = new StringBuffer("select count(*) from SMSCaptcha s where 1=1 ");
            if(!StringUtils.isEmpty(adminName)){
               sqld.append(" and s.adminname like:n ");
            }
            Query query = entityManager.createQuery(sqld.toString());
            if(!StringUtils.isEmpty(adminName)){
                query.setParameter("n", "%"+adminName+"%");
            }
            return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return 0;
    }

    /** 检验手机验证码是否正确, 验证码有效时间5分钟  */
    @SuppressWarnings("unchecked")
	public boolean isPhoneCaptcha(String phone, String captcha) {
        try {
            Query query = entityManager.createQuery("from SMSCaptcha where phone=?1 and UPPER(captcha)=?2  and TIMESTAMPDIFF(SECOND,createTime,now())<300 ").setParameter(1, phone).setParameter(2, captcha.toUpperCase());
            List<SMSCaptcha> list = query.getResultList();
            if(list!=null && list.size()>0){
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            log.error("isPhoneCaptcha fail",e);
            throw e;
        }
    }

}
